﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace Mole
{
    public partial class FrmInputURL : DockContent
    {
        private BindingList<UrlView> _urlViewList = new BindingList<UrlView>();
        public DockPanel _dockPanelMain;
        private String _badURL = String.Empty;
        private String _goodURL = String.Empty;
        private Boolean _ranScan = false;
        private Boolean _ranCheck = false;
        private Boolean _running = false;
        private UrlChecklist _UrlCheckList;
        private Int32 _urlTotal = 0;


        public FrmInputURL()
        {
            InitializeComponent();
            ProjectName();

            SetProgress(pbURLCheck, 0, 100, 0);
            
            //Event Triggers for checking url's
            _UrlCheckList = new UrlChecklist();
            _UrlCheckList.ProgressEvent += new UrlChecklist.ProgressEventHandler(UpdateProgress);
            _UrlCheckList.CompleteEvent +=new UrlChecklist.CompleteEventHandler(_UrlCheckList_CompleteEvent);

            dgvInputParsed.AutoGenerateColumns = false;
            dgvInputParsed.DataSource = _urlViewList;
            dgvInputParsed.AutoSize = false;
        }

        void _UrlCheckList_CompleteEvent(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                UrlChecklist urlCheck = e.Result as UrlChecklist;
                _UrlCheckList = urlCheck;
                FillGridView(urlCheck.List);

                if (_running)
                {
                    if (_UrlCheckList.List != null)
                    {
                        ChecksComplete(_UrlCheckList.List);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw;
            }
        }

        #region buttons
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (!_running)
            {
                _running = true;
                _ranScan = true;

                if (!_ranCheck)
                {

                    _badURL = "";
                    _goodURL = "";

                    List<String> UrlList = ParseText(textBox1.Text);
                    _urlTotal = UrlList.Count;

                    CheckURL(UrlList);
                    //event will be triggered after the checkurl to open the scan form.
                }
                else
                {
                    //check has already been done, start scanning
                    if (_UrlCheckList.List.Count > 0)
                    {
                        ChecksComplete(_UrlCheckList.List);
                    }
                }
            }
         }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (!_running)
            {
                _running = true;
                _ranCheck = true;

                //_badURL = "";
                //_goodURL = "";

                List<String> UrlList = ParseText(textBox1.Text);
                _urlTotal = UrlList.Count;

                _UrlCheckList.Create(UrlList);
                ChecksComplete(_UrlCheckList.List);
            }
        }

        private void txtProject_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();

            DialogResult result = folder.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtProject.Text = folder.SelectedPath;
            }
        }
        #endregion


        #region helper

        private void CheckURL(List<String> urlList)
        {
            _UrlCheckList.Create(urlList);
        }

        private void ProjectName()
        {
            DateTime dtNow = DateTime.Now;
            txtProject.Text = String.Format("{0:yyyy-MM-dd}", dtNow);
        }

        private List<String> ParseText(String input)
        {
            List<String> sList = new List<string>();
            string[] splitAry = input.Split('\n');
            
            //remove whitespace and \r
            foreach (String s in splitAry)
            {
                String str = s.Trim();
                if (!String.IsNullOrEmpty(str))
                {
                    sList.Add(str);
                }
            }
            return sList;
        }

        private void ChecksComplete(List<UrlCheck> UrlCheck)
        {

            List<UrlCheck> badList = new List<UrlCheck>();
            List<UrlCheck> goodList = new List<UrlCheck>();

            if (_ranScan)
            {
                if (!_ranCheck)
                {
                    foreach (UrlCheck url in _UrlCheckList.List)
                    {
                        if (!url.Valid)
                        {
                            badList.Add(url);
                        }
                        else
                        {
                            goodList.Add(url);
                        }
                    }
                }

                FillUrl(goodList);


                if (goodList.Count > 0)
                {
                    UrlSession session = new UrlSession();
                    session.SetUrlSession(txtProject.Text, goodList);

                    FrmSiteScan frmSiteScan = new FrmSiteScan(session);
                    frmSiteScan._dockPanelMain = _dockPanelMain;
                    frmSiteScan.Show(_dockPanelMain);
                    frmSiteScan.StartScan();
                }

                //if (badList.Count > 0)
                //{
                //    FrmInputURL badInput = new FrmInputURL();
                //    badInput.Text = "Invalid";
                //    badInput._dockPanelMain = _dockPanelMain;
                //    badInput.Show(_dockPanelMain);
                //    badInput.FillUrl(badList);
                //    //MessageBox.Show("Input contains invalid URLs");
                //}
            }
            else
            {
                {
                    foreach (UrlCheck url in _UrlCheckList.List)
                    {
                        if (!url.Valid)
                        {
                            badList.Add(url);
                        }
                        else
                        {
                            goodList.Add(url);
                        }
                    }

                    //textBox1.Text = _goodURL;

                    if (_badURL.Length > 0)
                    {
                        FrmInputURL badInput = new FrmInputURL();
                        badInput.Text = "Invalid";
                        badInput._dockPanelMain = _dockPanelMain;
                        badInput.Show(_dockPanelMain);
                        badInput.FillUrl(badList);
                        //MessageBox.Show("Input contains invalid URLs");
                    }
                }


                _running = false;
            }
        }

        private void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {

            SetProgress(pbURLCheck, 0, 100, e.ProgressPercentage);

        }

        private void SetProgress(ProgressBar pb, int min, int max, int value)
        {
            pb.Minimum = min;
            pb.Maximum = max;
            pb.Value = value;
        }

        public void FillUrl(String sURL)
        {
            textBox1.Text = sURL;
        }

        public void FillUrl(List<UrlCheck> urls)
        {
            string s = "";

            foreach (UrlCheck url in urls)
            {
                s += url.Host + "\r\n";
            }
            textBox1.Text = s;
        }

        public void FillGridView(List<UrlCheck> urls)
        {
            foreach (UrlCheck url in urls)
            {
                UrlView view = new UrlView(url);
                _urlViewList.Add(view);
            }

            textBox1.Visible = false;
            dgvInputParsed.Visible = true;

        }

        #endregion


    }
}
